package com.leiyuee.springbase.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@RestController
public class ExportController {




    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
      //一般是写线程池配置类 然后直接用
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10,20,
                30, TimeUnit.SECONDS,new LinkedBlockingDeque<>(100000),
                Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy()
        );


        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        try{
            response.setHeader("Content-disposition","attachment;filename=down_"+ URLEncoder.encode(System.currentTimeMillis()+".xlsx","utf-8"));
            int count = 1000000;
            int pageSize = 10000;
            ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
            List<CompletableFuture> completableFutures = new ArrayList<>();
            for (int i=0 ;i<(count/pageSize)+1;i++){
                int finalI = i;
                CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
                    List<Object> list = new ArrayList<>();//查询结果
                    if (list.isEmpty()) {
                        WriteSheet writeSheet = EasyExcel.writerSheet(finalI, "用户" + (finalI + 1)).head(Object.class)
                                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
                        synchronized (excelWriter) {
                            excelWriter.write(list, writeSheet);
                        }
                    }

                }, threadPoolExecutor);//需要一个线程池
                completableFutures.add(completableFuture);
            }
            for (CompletableFuture completableFuture:completableFutures){
                completableFuture.join();
            }
            excelWriter.finish();

        }catch (Exception e){
            throw  new RuntimeException(e);
        }finally {
            outputStream.flush();
            response.getOutputStream().close();
        }


    }
}
